package ij.hkust.QuickPALM;

import java.awt.Button;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import ij.*;
import ij.gui.NonBlockingGenericDialog;
import ij.measure.ResultsTable;
import ij.plugin.*;
import ij.plugin.filter.Analyzer;

/**
 * 
 * @author linshan
 *
 */

public class OutputSelectedRegion implements PlugIn
{
	ImagePlus imp;
	
	MyDialogs dg = new MyDialogs();
	MyFunctions fn = new MyFunctions();
	MyIO io = new MyIO();
	
	ResultsTable ptable = Analyzer.getResultsTable();
	ParticleSaver psave;
	java.util.concurrent.locks.Lock ptable_lock = new java.util.concurrent.locks.ReentrantLock();

	public void run(String arg)
	{
		imp = IJ.getImage();
		if (imp==null)
		{
            IJ.noImage();
            IJ.error("Need a reconstruction image opened");
			return;
		}
		
		if (fn.ptable.getCounter()==0 || !fn.ptable.columnExists(12))
		{
			IJ.error("Not able to detect a valid 'Particles Table', please load one");
			return;
		}
		
		double [] s = fn.ptable.getColumnAsDoubles(0);
		double [] x = fn.ptable.getColumnAsDoubles(1);
		double [] y = fn.ptable.getColumnAsDoubles(2);
		double [] x_ = fn.ptable.getColumnAsDoubles(3);
		double [] y_ = fn.ptable.getColumnAsDoubles(4);
		double [] z_ = fn.ptable.getColumnAsDoubles(5);	
		double [] frame = fn.ptable.getColumnAsDoubles(13);
		
		long nres = fn.ptable.getCounter();
		
		double pixelsize = fn.ptable.getColumnAsDoubles(3)[0]/x[0];
		double impcal = imp.getCalibration().getX(1);
		double magn = pixelsize/impcal;
		
		int xstart, xend, ystart, yend;
		Rectangle roi;
		
		roi = dg.rois[0].getBoundingRect();			
		xstart=(int) Math.round(roi.x/magn);
		xend=(int) Math.round((roi.x+roi.width)/magn);
		ystart=(int) Math.round(roi.y/magn);
		yend=(int) Math.round((roi.y+roi.height)/magn);
		
		int c=0;
				
		
		
		
		for (int n=0;n<nres;n++)
		{
			if (x[n]>xstart && x[n]<xend && y[n]>ystart && y[n]<yend)
			{
				ptable_lock.lock();
				ptable.incrementCounter();
				ptable.addValue("Intensity", s[n]);
				ptable.addValue("X (px)", x[n]);
				ptable.addValue("Y (px)", y[n]);
				ptable.addValue("X (nm)", x_[n]);
				ptable.addValue("Y (nm)", y_[n]);
				ptable.addValue("Z (nm)", z_[n]);
				
				ptable_lock.unlock();
				if (psave!=null)
				{
					psave.saveParticle(s[n], x[n], y[n], x_[n], y_[n], z_[n], 0, 0, 0, 0, 0, 0, 0, frame[n], 0, 0);
				}
			}
		}
		ptable.show("Results");
	}
}
